package com.unbook.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unbook.entity.User;
import com.unbook.entity.params.UserInfoParam;
import com.unbook.entity.params.UserParam;
import com.unbook.mapper.ISchoolMapper;
import com.unbook.mapper.IUserMapper;
import com.unbook.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<IUserMapper, User> implements IUserService {
    @Autowired
    IUserMapper userMapper;
    @Autowired
    ISchoolMapper schoolMapper;

    @Override
    public boolean initUser(UserParam param) {
        User user = User.builder()
            .uId(param.getUId())
            .openid(param.getOpenid())
            .unionid(param.getUnionid())
            .sessionKey(param.getSessionKey())
            .build();
        return userMapper.insert(user) > 0;
    }

    @Override
    public User saveUserInfo(String uId,UserInfoParam param) {
        User user = userMapper.selectById(uId);
        if(user != null){
            user.setHeadUrl(param.getHeadUrl());
            user.setName(param.getName());
            user.setSId(param.getSid());
            if(userMapper.updateById(user) > 0){
                if(user.getSId() != null){
                    user.setSchool(schoolMapper.selectById(user.getSId()));
                }
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean disable(String uId) throws Exception {
        User user = userMapper.selectById(uId);
        if(user != null){
            user.setStatus(0);
            return userMapper.updateById(user) > 0;
        }
        throw new Exception("未找到用户");
    }
    @Override
    public boolean unDisable(String uId) throws Exception {
        User user = userMapper.selectById(uId);
        if(user != null){
            user.setStatus(1);
            return userMapper.updateById(user) > 0;
        }
        throw new Exception("未找到用户");
    }
}
